package xyz.xtt.equity.service.impl;

import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import xyz.xtt.common.objects.DozerUtil;
import xyz.xtt.equity.constants.ErrorMessage;
import xyz.xtt.equity.entity.TblLuckPhonePool;
import xyz.xtt.equity.exception.ChainException;
import xyz.xtt.equity.mapper.TblLuckPhonePoolMapper;
import xyz.xtt.equity.service.ITblAssetEntitlementService;
import xyz.xtt.equity.service.ITblLuckPhonePoolService;
import xyz.xtt.equity.vo.LuckPhoneVo;

/**
 * @author dale
 * @since 2024/12/31
 **/
@Service
public class TblLuckPhonePoolServiceImpl extends ServiceImpl<TblLuckPhonePoolMapper, TblLuckPhonePool> implements ITblLuckPhonePoolService {
	private static final String PHONE_POOL_BATCH_NO_CACHE_KEY = "NFT:CACHE:PHONE:POOL:BATCH";

	@Autowired
	private ITblAssetEntitlementService assetEntitlementService;
	@Autowired
	private StringRedisTemplate redisTemplate;

	@Override
	public List<LuckPhoneVo> list(String uid, String id, Integer current, Integer pageSize, String city, String province) {

		Long Lid = Long.parseLong(id);
		// 校验是否已兑换权益 没有权益
		if (!assetEntitlementService.deliverCheck(uid, Lid)) {
			throw new ChainException(ErrorMessage.EQUITY_EXCHANGE_USER_WRONG);
		}

		// 查询当前有效批次号
		long batchNo = getCurrentBatchNo();

		LambdaQueryChainWrapper<TblLuckPhonePool> query = new LambdaQueryChainWrapper<>(baseMapper);
		query
				.eq(StringUtils.isNotBlank(province), TblLuckPhonePool::getProvince, province)
				.eq(StringUtils.isNotBlank(city), TblLuckPhonePool::getCity, city)
				.eq(TblLuckPhonePool::getBatchNo, batchNo);
		Long total = query.count();
		if (null != total && total > 10) {
			int current_size = (int) (total / 10L);
			if (2000 < current_size) {
				Random random = new Random();
				// 生成一个随机的整数
				int rand = random.nextInt(10);
				if (7 >= rand) {
					current_size = 2000;
				}
			}
			Random random = new Random();
			// 生成一个随机的整数
			current = random.nextInt(current_size);
		}

		List<TblLuckPhonePool> records = query.page(new Page<>(current, pageSize)).getRecords();

		return DozerUtil.transforList(records, LuckPhoneVo.class);
	}

	/**
	 * 获取当前有效批次号
	 * 
	 * @return
	 */
	private long getCurrentBatchNo() {
		// 优先从缓存获取
		String batchStr = redisTemplate.opsForValue().get(PHONE_POOL_BATCH_NO_CACHE_KEY);
		if (StringUtils.isNotBlank(batchStr)) {
			return Long.parseLong(batchStr);
		}

		// 缓存不存在是尝试从db获取
		QueryWrapper<TblLuckPhonePool> query = new QueryWrapper<>();
		query.orderByDesc("batch_no");
		Page<TblLuckPhonePool> page = baseMapper.selectPage(new Page<>(1, 1), query);
		if (page != null && page.getRecords().size() > 0) {
			return page.getRecords().get(0).getBatchNo();
		}
		return 0L;
	}

}
